var Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');

// 根据传入时间查找班次
exports.findShift = function (queryTime, projection, populate) {
    var deferred = Q.defer();

    if (!projection) {
        projection = {};
    }
    var entity = entityCollection.getEntity("Shift"),
        tempTime = new Date(queryTime),
        realTime = new Date(2000, 0, 1, tempTime.getHours(), tempTime.getMinutes(), tempTime.getSeconds()),
        orRealTime = new Date(2000, 0, 2, tempTime.getHours(), tempTime.getMinutes(), tempTime.getSeconds()),
        result = entity.Entity.findOne({
            $or: [{
                StartTime: { $lte: realTime },
                EndTime: { $gte: realTime }
            }, {
                StartTime: { $lte: orRealTime },
                EndTime: { $gte: orRealTime }
            }]
        }, projection);
    if (populate) {
        result = result.populate(populate);
    }

    result.then(function (record) {
        deferred.resolve(record);
    }, function () {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '查询班次错误';
        newErr.message = '查询班次失败，请检查查询参数！';
        deferred.reject(newErr);
    });

    return deferred.promise;
};